package engines.jpctae;

import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;
import android.content.Context;
import android.graphics.Color;
import android.opengl.GLSurfaceView;
import com.threed.jpct.Camera;
import com.threed.jpct.FrameBuffer;
import com.threed.jpct.Light;
import com.threed.jpct.Object3D;
import com.threed.jpct.Primitives;
import com.threed.jpct.SimpleVector;
import com.threed.jpct.Texture;
import com.threed.jpct.TextureManager;
import com.threed.jpct.World;
import com.threed.jpct.util.BitmapHelper;
import com.threed.jpct.util.MemoryHelper;

public class MyRenderer implements GLSurfaceView.Renderer {
	private JPCTAESkeletonActivity masterActivity = null;
	private Context masterContext = null;
	private FrameBuffer fb = null;
	private World world = null;
	private int back = Color.BLACK;
	private Light sun = null;
	private float touchTurn = 0;
	private float touchTurnUp = 0;
	private Object3D cube = null;

	public MyRenderer(JPCTAESkeletonActivity master, Context context) {
		this.masterActivity = master;
		this.masterContext = context;
	}

	public void setTurnValues(float tt, float ttUp) {
		this.touchTurn = tt;
		this.touchTurnUp = ttUp;
	}

	public void onDrawFrame(GL10 gl) {
		if (touchTurn != 0) {
			cube.rotateY(touchTurn);
			touchTurn = 0;
		}
		if (touchTurnUp != 0) {
			cube.rotateX(touchTurnUp);
			touchTurnUp = 0;
		}
		fb.clear(back);
		world.renderScene(fb);
		world.draw(fb);
		fb.display();
	}

	public void onSurfaceChanged(GL10 gl, int width, int height) {
		if (fb != null)
			fb.dispose();
		fb = new FrameBuffer(gl, width, height);
		if (masterActivity == null) {
			world = new World();
			world.setAmbientLight(120, 120, 120);
			sun = new Light(world);
			sun.setIntensity(250, 250, 250);
			// ************************************************
			Texture texture = new Texture(BitmapHelper.rescale(BitmapHelper
					.convert(masterContext.getResources().getDrawable(
							R.drawable.ic_launcher)), 64, 64));
			TextureManager.getInstance().addTexture("texture", texture);
			cube = Primitives.getCube(10);
			cube.calcTextureWrapSpherical();
			cube.setTexture("texture");
			cube.strip();
			cube.build();
			world.addObject(cube);
			Camera cam = world.getCamera();
			cam.moveCamera(Camera.CAMERA_MOVEOUT, 50);
			cam.lookAt(cube.getTransformedCenter());
			SimpleVector sv = new SimpleVector();
			sv.set(cube.getTransformedCenter());
			sv.y -= 100;
			sv.z -= 100;
			sun.setPosition(sv);
			MemoryHelper.compact();
			// ************************************************
		}
	}

	public void onSurfaceCreated(GL10 gl, EGLConfig config) {
	}
}